package com.unidt.www.module.system.dal.mysql.dept;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.unidt.www.framework.mybatis.core.mapper.BaseMapperX;
import com.unidt.www.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.unidt.www.module.system.controller.admin.dept.vo.dept.DeptListReqVO;
import com.unidt.www.module.system.dal.dataobject.dept.DeptDO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface DeptMapper extends BaseMapperX<DeptDO> {

    default List<DeptDO> selectList(DeptListReqVO reqVO) {
        return selectList(new LambdaQueryWrapperX<DeptDO>()
                .likeIfPresent(DeptDO::getName, reqVO.getName())
                .eqIfPresent(DeptDO::getStatus, reqVO.getStatus()));
    }

    default DeptDO selectByParentIdAndName(Long parentId, String name) {
        return selectOne(new LambdaQueryWrapper<DeptDO>()
                .eq(DeptDO::getParentId, parentId)
                .eq(DeptDO::getName, name));
    }

    default Long selectCountByParentId(Long parentId) {
        return selectCount(DeptDO::getParentId, parentId);
    }

    default List<DeptDO> selectListByParentId(Long deptId) {
        return selectList(DeptDO::getParentId, deptId);//传部门id进来，查找parentId,这条注释防正坤说是parentid要对应parentid。
    }

    @Select("SELECT COUNT(*) FROM system_dept WHERE update_time > #{maxUpdateTime}")
    Long selectCountByUpdateTimeGt(LocalDateTime maxUpdateTime);

    default DeptDO getByThirdId(String thirdDeptId){
        LambdaQueryWrapper<DeptDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DeptDO::getThirdId,thirdDeptId);
       return this.selectOne(lambdaQueryWrapper);
    };

     default Long getMaxCode(Long id){
         LambdaQueryWrapper<DeptDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
         lambdaQueryWrapper.eq(DeptDO::getParentId,id);
         lambdaQueryWrapper.isNotNull(DeptDO::getCode);
         lambdaQueryWrapper.eq(DeptDO::getDeleted,false);
         List<DeptDO> deptDOS =  this.selectList(lambdaQueryWrapper);
         if(!deptDOS.isEmpty()){
            Long maxCode =    deptDOS.stream().mapToLong(DeptDO::getCode).max().getAsLong();
            return  maxCode;
         }
         return Long.valueOf(0);
     };

    default  void updateCode(Long id, String code){

        LambdaUpdateWrapper<DeptDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(DeptDO::getCode,code);
        lambdaUpdateWrapper.eq(DeptDO::getId,id);
        this.update(null,lambdaUpdateWrapper);
    };
}
